package bank;

import java.util.Arrays;

public class _16ThreeSumClosest {
    public static int threeSumClosest(int[] nums, int target) {
        if(nums.length == 3){
            return nums[0] + nums[1] + nums[2];
        }
        Arrays.sort(nums);
        int closestNum = nums[0] + nums[1] + nums[2];
        //注意这里i的上限
        for (int i = 0; i < nums.length - 2; i++) {
            //这里i从左边遍历，左边的元素就不需要重复考虑了，所以left在i的右侧
            int left = i + 1, right = nums.length - 1;
            while (left < right){
                //先处理数据，再判断指针位移条件
                int threeSum = nums[left] + nums[right] + nums[i];
                if (Math.abs(threeSum - target) < Math.abs(closestNum - target)) {
                    closestNum = threeSum;
                }
                if (threeSum > target) {
                    right--;
                } else if (threeSum < target) {
                    left++;
                } else {
                    return target;
                }
            }
        }
        return closestNum;
    }
}
